<template>
  <div :class="['webview', isDark ? 'dark' : 'light']">
    <!-- 主内容区域 -->
    <div class="container">
      <!-- DocLinter 组件区域 -->
      <div class="doc">
        <div class="doc-title">
          <div>{{ i18n.total.replace('${count}', questionCount.toString()) }}</div>
          <div>
            <d-button variant="text" @click="toggle">
              <i class="icon-history"></i>
              {{ i18n.viewHistoryReport }}
            </d-button>
          </div>
        </div>
        
        <div>
          <d-tree
            v-if="treeData.length > 0"
            :data="treeData"
            class="tree"
            @node-click="onSelect"
          >
            <template #content="{ node }">
              <span>{{ node.title }}</span>
            </template>
          </d-tree>
          <div v-else class="empty-state">
            <i class="icon-empty"></i>
            <p>暂无数据</p>
          </div>
        </div>
        
        <!-- 问题详情区域 -->
        <div v-if="checkTextInfo()" class="footer">
          <div class="line" style="margin: 16px 0"></div>
          <div class="s-title">{{ i18n.originalText }}</div>
          <div class="block">{{ textInfo.originalText }}</div>
          <div class="s-title">{{ i18n.rule }}</div>
          <div class="block">{{ textInfo.rule }}</div>
          <div class="s-title">{{ i18n.reason }}</div>
          <div class="block">{{ textInfo.reason }}</div>
          <div class="s-title">{{ i18n.advice }}</div>
          <div class="block">
            <div>{{ textInfo.advice }}</div>
            <div class="block-operate">
              <div>
                <d-tooltip :content="i18n.compare">
                  <i class="icon-compare btn" @click="compare"></i>
                </d-tooltip>
                <d-tooltip :content="i18n.copy">
                  <i class="icon-copy btn" @click="copy"></i>
                </d-tooltip>
                <d-tooltip :content="i18n.replace">
                  <i class="icon-exchange btn" @click="replace"></i>
                </d-tooltip>
                <d-tooltip :content="i18n.disagree">
                  <i 
                    :class="['btn', likeIndex === 2 ? 'icon-close-filled reject-active' : 'icon-close']"
                    @click="disLikeOnChange"
                  ></i>
                </d-tooltip>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 反馈弹窗 -->
    <d-modal
      v-model="isOpen"
      :title="i18n.feedback"
      @confirm="submitFeedback"
      @cancel="() => { isOpen = false }"
    >
      <d-textarea
        ref="inputRef"
        v-model="feedback"
        :error="isError"
        :placeholder="i18n.feedbackInfo"
        :rows="4"
        @input="textareaOnChange"
      />
    </d-modal>
    
    <!-- 历史记录弹窗 -->
    <d-modal
      v-model="isOpenHistory"
      :title="i18n.checkRecord"
      width="80%"
      @confirm="() => { isOpenHistory = false }"
      @cancel="() => { isOpenHistory = false }"
    >
      <d-table
        :data="dataSource"
        size="sm"
        stripe
        border
        class="doc-linter-table"
        :max-height="400"
      >
        <d-column field="localPath" header="File Name" min-width="140px" show-overflow-tooltip />
        <d-column field="createTime" header="Create Time" min-width="160px" />
        <d-column field="userName" header="Creator" min-width="80px" />
        <d-column field="status" header="Status" min-width="100px" cellClass="status-column">
          <template #header>
            {{ i18n.status }}
          </template>
          <template #default="{ row }">
            <d-tag :type="getTagType(row.status)">
              {{ getStatusText(row.status) }}
            </d-tag>
          </template>
        </d-column>
        <d-column field="operate" header="Report" min-width="160px" cellClass="operate-column">
          <template #header>
            {{ i18n.report }}
          </template>
          <template #default="{ row }">
            <div class="table-operations">
              <d-button 
                size="sm" 
                variant="text" 
                :disabled="row.status !== 0 && row.status !== 4"
                @click="cancle(row.reportId)"
                class="operation-button"
              >
                <i class="icon-close"></i>
                {{ i18n.cancle }}
              </d-button>
              <d-button 
                size="sm" 
                variant="text" 
                :disabled="row.status !== 1"
                @click="viewReport(row.reportId)"
                class="operation-button"
              >
                <i class="icon-search"></i>
                {{ i18n.viewReport }}
              </d-button>
              <d-button 
                size="sm" 
                variant="text" 
                :disabled="row.status !== 1"
                @click="downLoad(row.reportId)"
                class="operation-button"
              >
                <i class="icon-download"></i>
                {{ i18n.download }}
              </d-button>
              <d-button 
                size="sm" 
                variant="text" 
                :disabled="row.status !== 1"
                @click="openOnlineReport(row.reportId)"
                class="operation-button"
              >
                <i class="icon-globe"></i>
                {{ i18n.viewOnlineReport }}
              </d-button>
            </div>
          </template>
        </d-column>
      </d-table>
      <div class="table-page">
        <d-pagination
          v-model:current="page"
          v-model:page-size="pageSize"
          :total="total"
          size="sm"
          show-size-changer
          show-jump-page
          @change="paginationOnChange"
        />
      </div>
    </d-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, computed, nextTick } from 'vue'
import 'vue-devui/tree/style.css'
import 'vue-devui/button/style.css'
import 'vue-devui/modal/style.css'
import 'vue-devui/textarea/style.css'
import 'vue-devui/table/style.css'
import 'vue-devui/tag/style.css'
import 'vue-devui/pagination/style.css'
import 'vue-devui/dropdown/style.css'
import 'vue-devui/tooltip/style.css'

// 常量定义
const THEME = {
  LIGHT: 1,
  DARK: 2,
}

const INDEX_MAP = {
  DEFAULT: 0,
  AGREE: 1,
  DISAGREE: 2,
}

const copyStatus = 3
const replaceStatus = 4
const DEFAULT_PAGE = 1
const DEFAULT_PAGE_SIZE = 10

// 响应式数据
const isDark = ref<boolean>(true)
const lang = ref<string>('en')
const isOpen = ref<boolean>(false)
const feedback = ref<string>('')
const isOpenHistory = ref<boolean>(false)
const likeIndex = ref<number>(INDEX_MAP.DEFAULT)
const inputRef = ref()
const isError = ref<boolean>(false)
const page = ref<number>(DEFAULT_PAGE)
const pageSize = ref<number>(DEFAULT_PAGE_SIZE)
const total = ref<number>(0)
const dataSource = ref<any[]>([])
const treeData = ref<any[]>([])
const questionCount = ref<number>(0)
const reportId = ref<number>(0)
const timer = ref<any>(null)

const textInfo = reactive({
  originalText: '',
  rule: '',
  reason: '',
  advice: '',
  fileName: '',
  line: '',
  defectId: '',
})

const pageInfo = ref({
  page: DEFAULT_PAGE,
  pageSize: DEFAULT_PAGE_SIZE,
})

// 国际化配置
const i18nConfig = {
  zh: {
    originalText: "原文",
    rule: "违反规则",
    reason: "违反原因",
    advice: "修复建议",
    compare: "对比",
    copy: "复制",
    replace: "替换",
    agree: "赞",
    disagree: "拒绝",
    checkRecord: "检查记录",
    fileName: "文件名",
    createTime: "创建时间",
    creator: "创建者",
    status: "状态",
    success: "成功",
    executing: "检查执行中",
    queueing: "排队中",
    timeout: "超时",
    failed: "失败",
    report: "检查报告",
    download: "下载",
    viewReport: "查看检查结果",
    viewOnlineReport: "查看在线报告",
    viewHistoryReport: "查看历史检查报告",
    copySuccessful: "已复制",
    total: "总计：${count}个缺陷",
    feedback: "反馈",
    feedbackInfo: "请输入您的问题",
    feedbackErrorInfo: "反馈信息不能为空",
    submit: "提交",
    replaceSuccess: "替换操作成功",
    replaceFailed: "替换操作失败",
    totalReportCount: "总计：${count}",
    createTaskSuccess: "创建任务成功",
    createTaskFailed: "创建任务失败",
    fileNotExist: "当前文件不存在",
    submitSuccess: "提交成功",
    loginIn: "登录",
    logOut: '注销',
    loginFirst: '请先登录',
    cancle: '取消',
    cancleSuccess: '任务取消成功'
  },
  en: {
    originalText: "Original Text",
    rule: "Rules",
    reason: "Reason",
    advice: "Advice",
    compare: "Compare",
    copy: "Copy",
    replace: "Replace",
    agree: "Agree",
    disagree: "Disagree",
    checkRecord: "Record",
    fileName: "File Name",
    createTime: "Create Time",
    creator: "Creator",
    status: "Status",
    success: "Success",
    timeout: "Timeout",
    executing: "Executing",
    queueing: "Queueing",
    failed: "Failed",
    report: "Report",
    download: "Download",
    viewReport: "View Report",
    viewOnlineReport: "View Online Report",
    viewHistoryReport: "View History Report",
    copySuccessful: "Copied",
    total: "Total: ${count} defects",
    feedback: "Feedback",
    feedbackInfo: "Please enter your question",
    submit: "submit",
    feedbackErrorInfo: "Feedback information cannot be empty",
    replaceSuccess: "Replacement operation successful",
    replaceFailed: "Replacement operation failed",
    totalReportCount: "Total: ${count}",
    createTaskSuccess: "Task created successfully",
    createTaskFailed: "Task creation failed",
    fileNotExist: "The current file does not exist",
    submitSuccess: "Submitted successfully",
    loginIn: "Login in",
    logOut: 'Log out',
    loginFirst: 'please log in first',
    cancle: 'cancel',
    cancleSuccess: 'Canceled successfully'
  }
}

// 计算属性
const i18n = computed(() => {
  return i18nConfig[lang.value] || i18nConfig.en
})


// 工具方法
const getTagType = (status: number) => {
  if (status === 0) return 'info'
  if (status === 1) return 'success'
  if (status === 2) return 'danger'
  if (status === 4) return 'warning'
  if (status === 5) return 'default'
  return 'default'
}

const getStatusText = (status: number) => {
  if (status === 0) return i18n.value.executing
  if (status === 1) return i18n.value.success
  if (status === 2) return i18n.value.failed
  if (status === 4) return i18n.value.queueing
  if (status === 5) return i18n.value.cancle
  return i18n.value.timeout
}

// 方法定义
const onSelect = (node: any) => {
  if (node?.isLeaf) {
    Object.assign(textInfo, {
      originalText: node.problematicSentence,
      rule: node.ruleName,
      reason: node.reason,
      advice: node.fixedSentence,
      line: node.problematicLineNum,
      fileName: node.filePath,
      defectId: node.defectId,
    })
    if (window.vscode) {
      window.vscode.postMessage({
        messageType: 'goToFile',
        data: {
          filePath: node.filePath,
          line: node.problematicLineNum,
        },
      })
      window.vscode.postMessage({
        messageType: 'queryStatus',
        data: {
          defectId: node.defectId,
        },
      })
    }
  }
}

const viewReport = (id: number) => {
  reportId.value = id
  if (window.vscode) {
    window.vscode.postMessage({
      messageType: 'viewReport',
      data: id,
    })
  }
}

const downLoad = (id: number) => {
  reportId.value = id
  if (window.vscode) {
    window.vscode.postMessage({
      messageType: 'downLoad',
      data: id,
    })
  }
}

const cancle = (id: number) => {
  reportId.value = id
  if (window.vscode) {
    window.vscode.postMessage({
      messageType: 'cancel',
      data: id,
    })
  }
}

const openOnlineReport = (id: number) => {
  if (window.vscode) {
    window.vscode.postMessage({
      messageType: 'openExternal',
      data: id,
    })
  }
}

const copy = () => {
  if (
    textInfo.originalText.length > 0 &&
    textInfo.advice.length > 0 &&
    window.vscode
  ) {
    window.vscode.postMessage({
      messageType: 'copy',
      data: textInfo.advice,
    })
    if (window.vscode) {
      window.vscode.postMessage({
        messageType: 'raise',
        data: {
          status: copyStatus,
          reportId: reportId.value,
          defectId: textInfo.defectId,
        },
      })
    }
  }
}

const compare = () => {
  if (
    textInfo.originalText.length > 0 &&
    textInfo.advice.length > 0 &&
    window.vscode
  ) {
    window.vscode.postMessage({
      messageType: 'compare',
      data: {
        filePath: textInfo.fileName,
        line: textInfo.line,
        originText: textInfo.originalText,
        fixText: textInfo.advice,
      },
    })
  }
}

const replace = () => {
  if (
    textInfo.originalText.length > 0 &&
    textInfo.advice.length > 0 &&
    window.vscode
  ) {
    window.vscode.postMessage({
      messageType: 'replace',
      data: {
        filePath: textInfo.fileName,
        line: textInfo.line,
        originText: textInfo.originalText,
        fixText: textInfo.advice,
      },
    })
    if (window.vscode) {
      window.vscode.postMessage({
        messageType: 'raise',
        data: {
          status: replaceStatus,
          reportId: reportId.value,
          defectId: textInfo.defectId,
        },
      })
    }
  }
}

const fetchData = (curPage: number, curPageSize: number) => {
  console.log("============================")
  if (window.vscode) {
    window.vscode.postMessage({
      messageType: 'fetchRecord',
      data: {
        page: curPage,
        pageSize: curPageSize,
      },
    })
  }
}

const disLikeOnChange = () => {
  if ([INDEX_MAP.DEFAULT, INDEX_MAP.AGREE].includes(likeIndex.value)) {
    isOpen.value = true
    feedback.value = ''
  } else {
    if (window.vscode) {
      window.vscode.postMessage({
        messageType: 'raise',
        data: {
          status: INDEX_MAP.DEFAULT,
          reportId: reportId.value,
          defectId: textInfo.defectId,
        },
      })
    }
  }
}

const submitFeedback = () => {
  if (feedback.value.trim() === '') {
    showMessage('error', i18n.value.feedbackErrorInfo)
    nextTick(() => {
      if (inputRef.value) {
        inputRef.value.focus()
      }
    })
    isError.value = true
    return
  }
  if (window.vscode) {
    window.vscode.postMessage({
      messageType: 'raise',
      data: {
        status: INDEX_MAP.DISAGREE,
        reportId: reportId.value,
        defectId: textInfo.defectId,
        reason: feedback.value,
      },
    })
  }
  isOpen.value = false
}

const textareaOnChange = () => {
  isError.value = false
}

const toggle = () => {
  isOpenHistory.value = true
  page.value = DEFAULT_PAGE
  pageSize.value = DEFAULT_PAGE_SIZE
  fetchData(DEFAULT_PAGE, DEFAULT_PAGE_SIZE)
}

const paginationOnChange = (curPage: number, curPageSize: number) => {
  page.value = curPage
  pageSize.value = curPageSize
  fetchData(curPage, curPageSize)
}

const checkTextInfo = () => {
  const { originalText, reason, rule, advice } = textInfo
  return originalText && reason && rule && advice
}

const showMessage = (type: string, content: string) => {
  // 使用 DevUI 的消息提示或者简单的 console.log
  console.log(`${type}: ${content}`)
  if (window.vscode) {
    window.vscode.postMessage({
      messageType: type,
      data: content,
    })
  }
}

// 消息监听处理
const handleMessage = (message: any) => {
  const { messageType, data } = message.data
  
  switch (messageType) {
    case 'langCallback':
      lang.value = data?.includes('zh') ? 'zh' : 'en'
      break
    case 'themeCallback':
      isDark.value = data === THEME.DARK
      break
    case 'copyCallback':
      showMessage('success', i18n.value.copySuccessful)
      break
    case 'gotoFileCallback':
      showMessage('error', i18n.value.fileNotExist)
      break
    case 'queryStatusCallback':
      likeIndex.value = data.status
      break
    case 'raiseCallback':
      let { status } = data
      if (status === copyStatus || status === replaceStatus) {
        status = INDEX_MAP.AGREE
      }
      likeIndex.value = status
      if (status === INDEX_MAP.DISAGREE) {
        showMessage('success', i18n.value.submitSuccess)
      }
      break
    case 'createCheckTask':
      if (data) {
        showMessage('success', i18n.value.createTaskSuccess)
        toggle()
        timer.value = setInterval(() => {
          const { page, pageSize } = pageInfo.value
          fetchData(page, pageSize)
        }, 10000)
      } else {
        showMessage('error', i18n.value.createTaskFailed)
      }
      break
    case 'fetchRecordCallback':
      total.value = data.total
      const records = data.records.map((x: any) => ({
        key: x.reportId,
        ...x,
      }))
      console.log("records", records)
      dataSource.value = records
      let flag = true
      for (const item of records) {
        if (item.status === 0) {
          flag = false
        }
      }
      if (flag && timer.value) {
        clearInterval(timer.value)
      }
      break
    case 'viewReportCallback':
      isOpenHistory.value = false
      questionCount.value = data.defectCount
      // 重置textInfo
      Object.assign(textInfo, {
        originalText: '',
        rule: '',
        reason: '',
        advice: '',
        fileName: '',
        line: '',
        defectId: '',
      })
      const fileDefectList = data.fileDefectList || []
      const list: any[] = []
      let cnt = 1
      for (const item of fileDefectList) {
        list.push({
          key: cnt.toString(),
          title: item.fileName,
          children: [],
        })
        if (item.ruleDefectList) {
          for (const item2 of item.ruleDefectList) {
            const children: any[] = []
            if (item2.ruleDefectList) {
              for (const item3 of item2.ruleDefectList) {
                cnt += 1
                children.push({
                  key: cnt.toString(),
                  title: `${item3.problematicSentence}(${item3.problematicLineNum})`,
                  children: [],
                  filePath: item.fileName,
                  isLeaf: true,
                  defectId: item3.defectId,
                  ...item3,
                })
              }
            }
            cnt += 1
            list[list.length - 1].children.push({
              key: cnt.toString(),
              title:
                item2.defectCount > 0
                  ? `${item2.ruleName}[${item2.defectCount}]`
                  : `${item2.ruleName}`,
              children: children,
            })
          }
        }
        cnt += 1
      }
      for (const item of list) {
        let sum = 0
        for (const item2 of item.children || []) {
          sum += item2.children?.length || 0
        }
        if (sum > 0) {
          item.title = `${item.title}[${sum}]`
        }
      }
      treeData.value = list
      break
    case 'cancelCallback':
      showMessage('success', i18n.value.cancleSuccess)
      break
  }
}

// 生命周期
onMounted(() => {
  if (window.vscode) {
    window.vscode.postMessage({ messageType: 'lang' })
    window.vscode.postMessage({ messageType: 'theme' })
  }
  
  // 监听页面变化
  pageInfo.value.page = page.value
  pageInfo.value.pageSize = pageSize.value
  
  // 设置定时器
  timer.value = setInterval(() => {
    const { page: currentPage, pageSize: currentPageSize } = pageInfo.value
    fetchData(currentPage, currentPageSize)
  }, 10000)
  
  // 初始化数据
  fetchData(1, 10)
  
  // 添加消息监听
  window.addEventListener('message', handleMessage)
})

onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value)
  }
  window.removeEventListener('message', handleMessage)
})
</script>

<style scoped>
.webview {
  font-size: 15px;
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.webview.light .line {
  background-color: #e9e9e9;
}

.webview.light .menu-item {
  color: #333 !important;
}

.webview.light .menu-item:hover {
  color: #000 !important;
}

.webview.light .doc .block {
  background-color: #fff !important;
  color: #000;
}

.line {
  background-color: #393939;
  height: 1px;
}

.container {
  flex: 1;
  padding: 16px;
  overflow: auto;
}

.doc .doc-title {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.doc .tree {
  padding: 8px;
  max-height: 400px;
  overflow: auto;
  font-size: 14px;
  border: 1px solid #393939;
  border-radius: 4px;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #666;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
  display: block;
}

.doc .block {
  padding: 16px;
  background-color: #212121;
  margin: 8px 0 20px 0;
  border-radius: 4px;
  color: #fff;
}

.doc .block .block-operate {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 16px;
}

.doc .block .block-operate > div {
  display: flex;
  align-items: center;
  gap: 16px;
}

.doc .block .block-operate .btn {
  opacity: 0.7;
  cursor: pointer;
  font-size: 16px;
  transition: opacity 0.2s;
}

.doc .block .block-operate .btn:hover {
  opacity: 1;
}

.reject-active {
  color: #ff4d4f !important;
  opacity: 1 !important;
}

.table-page {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.table-operations {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.table-operations .operation-button {
  padding: 2px 6px;
  font-size: 12px;
  border-radius: 4px;
}

.table-operations .operation-button:not(:disabled):hover {
  background-color: rgba(64, 150, 255, 0.1);
}

.s-title {
  font-weight: bold;
  margin-bottom: 8px;
  font-size: 14px;
}

/* DevUI 组件样式覆盖 */
:deep(.devui-tree-node-content) {
  padding: 4px 8px;
  border-radius: 4px;
}

:deep(.devui-tree-node-content:hover) {
  background-color: rgba(64, 150, 255, 0.1);
}

:deep(.doc-linter-table) {
  width: 100%;
  font-size: 12px;
  border-radius: 6px;
  overflow: hidden;
  table-layout: fixed;
}

:deep(.doc-linter-table .devui-table-cell) {
  padding: 8px 12px;
  word-break: break-all;
  white-space: normal;
}

:deep(.doc-linter-table .devui-table-header) {
  position: sticky;
  top: 0;
  z-index: 2;
}

:deep(.doc-linter-table th) {
  background-color: var(--devui-base-bg, #f5f5f5);
  font-weight: 600;
  color: var(--devui-text, #252b3a);
  padding: 10px 12px;
  border-bottom: 1px solid var(--devui-dividing-line, #dfe1e6);
}

:deep(.doc-linter-table .status-column) {
  text-align: center;
}

.webview.dark :deep(.doc-linter-table th) {
  background-color: #2a2a2a;
  color: #e0e0e0;
  border-bottom: 1px solid #3a3a3a;
}

.webview.dark :deep(.doc-linter-table) {
  border-color: #3a3a3a;
}

.webview.dark :deep(.doc-linter-table td) {
  border-color: #3a3a3a;
}
</style>
